package com.okilo.online.app.fmt

import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import androidx.core.net.toUri
import com.okilo.online.app.R
import com.okilo.online.app.act.OkiloPinPayStatusAct
import com.okilo.online.app.common.OkiloComFmt
import com.okilo.online.app.databinding.OkiloTabFmtRepayBinding
import com.okilo.online.app.databinding.OkiloTabFmtRepayDetailsChildItemBinding
import com.okilo.online.app.event.OkiloEventData
import com.okilo.online.app.event.OkiloEventPointType
import com.okilo.online.app.event.room.OkiloPointManager
import com.okilo.online.app.tools.apt.OkiloOnSingleClickListener
import com.okilo.online.app.tools.extensions.addCommasFromEndRegex
import com.okilo.online.app.tools.helper.OkiloConfigCustomerHp
import com.okilo.online.app.tools.helper.OkiloConfigProcessHp
import com.okilo.online.app.dialog.OkiloTipsDlog
import com.okilo.online.app.pet.OkiloLoanPet
import com.okilo.online.app.pet.view.IOkiloLoan
import org.json.JSONObject
import java.math.BigDecimal

/**
 * OkiloLoan
 * @Author wwdeng
 * @CreateTime: 2024/12/10 14:53
 * @Annotation：待还款
 */
class OkiloTabRepayFmt : OkiloComFmt(), IOkiloLoan.IOkiloPay {
    private var _binding: OkiloTabFmtRepayBinding? = null
    //公告提示
    private var noticeDialog: OkiloTipsDlog? = null
    //待还款信息
    private var okiloRepayPet: OkiloLoanPet? = null

    override val pageName: String = "Repay_Page"

    override fun createOkiloContentView(inflater: LayoutInflater): View? {
        _binding = OkiloTabFmtRepayBinding.inflate(layoutInflater)
        return _binding?.root
    }

    override fun initializeOkiloViews() {
        val binding = _binding ?: return
        binding.repayPageRefreshLayout.setColorSchemeResources(R.color.okilo_color_theme, R.color.okilo_color_ff6200ee)
        binding.okiloRepayDetailsLayout.visibility = View.GONE
        binding.btnRepay.visibility = View.GONE
        //不存在待还款信息
        binding.okiloRepayNoDataLayout.visibility = View.GONE
    }

    override fun setupOkiloEventListeners() {
        _binding?.repayPageRefreshLayout?.setOnRefreshListener {
            publishEventData(OkiloEventData(OkiloEventData.TYPE.OKILO_PROCESS_REFRESH))
        }
        _binding?.btnRepay?.setOnClickListener(object : OkiloOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.LOAN_REPAY,pageName)
                // TODO: 还款按钮 需上报所有埋点
                OkiloPointManager.getInstance().manualReport()

                if (okiloRepayPet == null){
                    okiloRepayPet = OkiloLoanPet(this@OkiloTabRepayFmt)
                }
                showOkiloLoading()
                okiloRepayPet?.gOkiloPayLinkRequest(this@OkiloTabRepayFmt)
            }
        })
    }

    override fun loadOkiloData() {
        onOkiloRepayRefreshData()
    }

    /**
     * 刷新待还款数据
     */
    fun onOkiloRepayRefreshData(){
        val binding = _binding ?: return
        //待还款
        val isRepay = OkiloConfigProcessHp.iOkiloApplyOrderRepay()
        if (isRepay){
//            okiloRepayPet?.gOkiloRepayInfoRequest(this)
            binding.okiloRepayNoDataLayout.visibility = View.GONE
        } else {
            hideOkiloLoading()
            binding.okiloRepayDetailsLayout.visibility = View.GONE
            binding.btnRepay.visibility = View.GONE
            //不存在待还款信息
            binding.okiloRepayNoDataLayout.visibility = View.VISIBLE
        }
    }

    /**
     * 设置还款信息
     */
    private fun sOkiloLoadRepayInfo(data: JSONObject){
        val binding = _binding ?: return

        binding.okiloRepayTotalText.text = BigDecimal(data.optString("repayAmount")).stripTrailingZeros().toPlainString().addCommasFromEndRegex()
        binding.okiloRepayDateText.text = data.optString("repayDate")

        //逾期天数
        val overdueDay = data.optInt("overdueDay",0)
        if (overdueDay > 0){//已逾期 - 逾期天数
            binding.okiloRepayStatus.text = String.format(getString(R.string.okilo_repay_info_status_days_overdue),"$overdueDay")
            binding.okiloRepayStatus.setTextColor(getColor(R.color.okilo_color_ffe84444))
        } else {//未逾期 - 剩余还款天数
            val remainDay = data.optString("remainDay")
            try {
                if (remainDay.toInt() > 3){
                    binding.okiloRepayStatus.text = getString(R.string.okilo_repay_info_status_normal)
                    binding.okiloRepayStatus.setTextColor(getColor(R.color.okilo_color_ff00ce4e))
                } else {
                    binding.okiloRepayStatus.text = String.format(getString(R.string.okilo_repay_info_status_days_left), remainDay)
                    binding.okiloRepayStatus.setTextColor(getColor(R.color.okilo_color_fff79617))
                }
            } catch (e: Exception){
                binding.okiloRepayStatus.text = String.format(getString(R.string.okilo_repay_info_status_days_left), remainDay)
                binding.okiloRepayStatus.setTextColor(getColor(R.color.okilo_color_fff79617))
            }
        }

        binding.repayItemListLayout.removeAllViews()
        val detailItemList = data.optJSONArray("detailItemList")
        detailItemList?.let { itemList ->
            for (i in 0..< itemList.length()){
                val childItem = itemList.optJSONObject(i)
                val childView = OkiloTabFmtRepayDetailsChildItemBinding.inflate(layoutInflater)
                childView.textDetailsTitle.text = childItem.optString("showName")
                childView.textDetailsTitle.setTextColor(getColor(R.color.okilo_color_ff7a7a7a))
                childView.textDetailsValue.text = childItem.optString("showDetail")
                childView.textDetailsValue.setTextColor(getColor(R.color.okilo_color_ff222222))

                childView.textOldValue.visibility = View.GONE
                if (childItem.has("oldDetail")){
                    childView.textOldValue.visibility = View.VISIBLE
                    childView.textOldValue.text = childItem.optString("oldDetail")
                }
                childView.discountLayout.visibility = View.GONE
                if (childItem.has("discount")){
                    childView.discountLayout.visibility = View.VISIBLE
                    childView.textDiscount.text = childItem.optString("discount")
                }

                childView.viewLine.visibility = View.VISIBLE
                if (i == itemList.length() - 1){
                    childView.viewLine.visibility = View.GONE
                }
                binding.repayItemListLayout.addView(childView.root)
            }
        }
        binding.okiloRepayDetailsLayout.visibility = View.VISIBLE
        binding.btnRepay.visibility = View.VISIBLE

        //公告信息
        sOkiloNoticeDialog()
    }

    /**
     * 设置还款信息
     */
    override fun sOkiloPayDataCallback(data: JSONObject) {
        hideOkiloLoading()
        var linkUrl = data.optString("url","")
        if (linkUrl.isEmpty()){
            linkUrl = data.optString("repayUrl","")
        }
        //没有还款链接 - 需要进入还款状态页查询还款状态
        if (linkUrl.isEmpty()){
            val thirdOrderId = data.optString("thirdOrderId")
            if (thirdOrderId.isEmpty()){
                showOkiloToast("Transaction id is empty")
                return
            }
            sOkiloPayStatusAction(thirdOrderId)
        } else {
            sOkiloPayLink(linkUrl)
        }
    }

    /**
     * 链接还款
     */
    private fun sOkiloPayLink(linkUrl: String){
        val uri = linkUrl.toUri()
        val intent = Intent(Intent.ACTION_VIEW, uri)
        startActivity(intent)
    }

    /**
     * pin还款
     */
    private fun sOkiloPayStatusAction(thirdOrderId: String){
        OkiloPinPayStatusAct.Companion.start(requireContext(),thirdOrderId,_binding?.okiloRepayDateText?.text.toString())
    }

    /**
     * 公告提示
     */
    private fun sOkiloNoticeDialog(){
        //需要检验手机号，不显示公告信息
        if (OkiloConfigProcessHp.iOkiloCheckSmsFlag() || OkiloConfigProcessHp.iOkiloCheckWhatsAppFlag()){
            return
        }
        // 检查是否可以显示公告提示 || 确保页面没有关闭
        if (!iOkiloShowNoticeDialog() || !isActive()) {
            return
        }

        val noticeInfo = OkiloConfigCustomerHp.tOkiloApplyNoticeInfo() ?: return
        // 更新显示次数
        OkiloConfigCustomerHp.showOkiloNoticeCount += 1
        noticeDialog = OkiloTipsDlog(
            requireContext(),
            pageName,
            object : OkiloTipsDlog.IOkiloTipsClickCallback {
                override fun onClick(view: View?) {
                    addEventPointRequestAction(
                        OkiloEventPointType.OKILO_CLICK_TRACK.NOTICE_CONFIRM,
                        pageName
                    )
                }
            })
        noticeDialog?.setOnDismissListener {

        }
        noticeDialog?.let { dialog ->
            dialog.setCancelable(true)
            dialog.setCanceledOnTouchOutside(true)
            dialog.show()
            dialog.iOkiloDlogTipsDoubleButton(false)
            dialog.sOkiloDlogTipsIconResource(R.mipmap.okilo_dlog_notice_icon)
            dialog.sOkiloDlogTipsTitleText(noticeInfo.optString("noticeTitle"))
            dialog.sOkiloDlogTipsMsgText(noticeInfo.optString("noticeText"))
            dialog.sOkiloDlogTipsButtonConfirmText(getString(R.string.okilo_btn_confirm))
        }
    }

    /**
     * 检查是否应该显示通知对话框
     */
    private fun iOkiloShowNoticeDialog(): Boolean {
        if (!OkiloConfigCustomerHp.iOkiloApplyNoticeShow()) {
            return false
        }

        val noticeInfo = OkiloConfigCustomerHp.tOkiloApplyNoticeInfo() ?: return false
        val showNum = noticeInfo.optInt("num", 1)
        val num = OkiloConfigCustomerHp.showOkiloNoticeCount

        if (num >= showNum) {
            return false
        }
        // 检查对话框是否已经在显示
        if (noticeDialog?.isShowing == true) {
            return false
        }
        return true
    }

    /**
     * 检查 Fragment 是否处于活跃状态
     */
    private fun isActive(): Boolean {
        return isAdded &&
                !isDetached &&
                activity != null &&
                !requireActivity().isFinishing &&
                !requireActivity().isDestroyed
    }

    override fun onOkiloPublishEvent(event: OkiloEventData) {
        super.onOkiloPublishEvent(event)
        when(event.eventType){
            OkiloEventData.TYPE.OKILO_PROCESS_REFRESHED,
            OkiloEventData.TYPE.OKILO_DATA_REFRESH -> {//收到刷新数据通知
                onOkiloRepayRefreshData()
            }
            OkiloEventData.TYPE.OKILO_REPAY_INFO_REFRESHED -> {//待还款信息刷新完成
                hideOkiloLoading()
                val data = event.eventData
                sOkiloLoadRepayInfo(data)
            }
            OkiloEventData.TYPE.OKILO_HTTP_REQUEST_ERROR -> {
                hideOkiloLoading()
            }
            else -> {
            }
        }
    }

    override fun hideOkiloLoading() {
        super.hideOkiloLoading()
        _binding?.repayPageRefreshLayout?.isRefreshing = false
    }

    override fun onDestroy() {
        super.onDestroy()
        // TODO: 待还款关闭 需上报所有埋点
        OkiloPointManager.getInstance().manualReport()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}